﻿using Dapper;
using MSXML2;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlKata.Execution;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using U8WebService.Models;
using static U8WebService.BLL.U8_WarehouseManagement;

namespace U8WebService.Common
{
    public class U8APIHelper
    {
        public static void FormatDom(ref MSXML2.DOMDocument SourceDom, int rows, string editprop)
        {
            //IXMLDOMElement element;
            //IXMLDOMElement ele_head;
            IXMLDOMElement ele_body;
            //IXMLDOMNode nd;
            //MSXML2.DOMDocument tempnd;
            IXMLDOMNodeList ndheadlist;
            IXMLDOMNodeList ndbodylist;
            //DistDom.loadXML("SourceDom.xml");
            String Filedname;
            //'格式部分
            ndheadlist = SourceDom.selectNodes("//s:Schema/s:ElementType/s:AttributeType");
            ndbodylist = SourceDom.selectNodes("//rs:data/z:row");
            if (ndbodylist.length == 0)
            {
                ele_body = SourceDom.createElement("z:row");
                //ele_body.setAttribute("id","");
                for (int i = 0; i <= rows; i++)
                {
                    SourceDom.selectSingleNode("//rs:data").appendChild(ele_body);
                }

                //SourceDom.selectSingleNode("//rs:data/z:row").s
            }
            ndbodylist = SourceDom.selectNodes("//rs:data/z:row");
            foreach (IXMLDOMElement body in ndbodylist)
            {
                foreach (IXMLDOMElement head in ndheadlist)
                {
                    Filedname = head.attributes.getNamedItem("name").nodeValue + "";
                    if (body.attributes.getNamedItem(Filedname) == null)
                        //  '若没有当前元素，就增加当前元素
                        body.setAttribute(Filedname, "");
                    switch (head.lastChild.attributes.getNamedItem("dt:type").nodeValue.ToString())
                    {
                        case "number":
                        case "float":
                        case "boolean":
                            if (body.attributes.getNamedItem(Filedname).nodeValue.ToString().ToUpper() == "false".ToUpper())
                                body.setAttribute(Filedname, 0);
                            break;
                        default:
                            if (body.attributes.getNamedItem(Filedname).nodeValue.ToString().ToUpper() == "否".ToUpper())
                                body.setAttribute(Filedname, 0);
                            break;
                    }
                }
                if (editprop != "")
                    body.setAttribute("editprop", editprop);
            }
        }
        public static void AddDomDataRow(ref MSXML2.DOMDocument SourceDom, int rows, string editprop)
        {
            //IXMLDOMElement element;
            //IXMLDOMElement ele_head;
            IXMLDOMElement ele_body;
            //IXMLDOMNode nd;
            //MSXML2.DOMDocument tempnd;
            IXMLDOMNodeList ndheadlist;
            IXMLDOMNodeList ndbodylist;
            //DistDom.loadXML("SourceDom.xml");
            String Filedname;
            //'格式部分
            ndheadlist = SourceDom.selectNodes("//s:Schema/s:ElementType/s:AttributeType");
            ndbodylist = SourceDom.selectNodes("//rs:data/z:row");

            //增加z:row节点
            for (int i = 0; i < rows; i++)
            {
                ele_body = SourceDom.createElement("z:row");
                SourceDom.selectSingleNode("//rs:data").appendChild(ele_body);
            }

            ndbodylist = SourceDom.selectNodes("//rs:data/z:row");
            foreach (IXMLDOMElement body in ndbodylist)
            {
                foreach (IXMLDOMElement head in ndheadlist)
                {
                    Filedname = head.attributes.getNamedItem("name").nodeValue + "";
                    if (body.attributes.getNamedItem(Filedname) == null)
                        //  '若没有当前元素，就增加当前元素
                        body.setAttribute(Filedname, "");
                    switch (head.lastChild.attributes.getNamedItem("dt:type").nodeValue.ToString())
                    {
                        case "number":
                        case "float":
                        case "boolean":
                            if (body.attributes.getNamedItem(Filedname).nodeValue.ToString().ToUpper() == "false".ToUpper())
                                body.setAttribute(Filedname, 0);
                            break;
                        default:
                            if (body.attributes.getNamedItem(Filedname).nodeValue.ToString().ToUpper() == "否".ToUpper())
                                body.setAttribute(Filedname, 0);
                            break;
                    }
                }
                if (editprop != "")
                    body.setAttribute("editprop", editprop);
            }
        }
        /// <summary>
        /// 获取销售出库中的单据号和主子表id
        /// </summary>
        /// <param name="childNum">字表个数</param>
        /// <param name="CardNumber">单据单号类型编码</param>
        /// <param name="cVouchType">id中单据类型</param>
        /// <param name="cTVCode">单据单号</param>
        /// <param name="fatherId">主表id</param>
        /// <param name="childId">字表id</param>
        public static void GetIndex_FromProcedure(int childNum, string CardNumber, string cVouchType, out string cNumber, out string cTVCode, out string fatherId, out string childId)
        {
            // 获取单据号
            var u8Db = new Katabase().U8Db();
            //CardNumber = "0303"(销售出库单); CardNumber = "0304"(调拨单);
            var codeNumberDic = new Dictionary<string, object>();
            var codeNumberObject =
               u8Db
               .Query("VoucherNumber").Where("CardNumber", CardNumber)
               .Select("Prefix1", "Prefix1Len", "Prefix1Rule", "GlideLen")
               .Get<object>().FirstOrDefault();
            //.Get<Dictionary<string, string>>().FirstOrDefault();
            codeNumberDic = JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(codeNumberObject));
            var GlideLen = codeNumberDic["GlideLen"].ToString();//流水号长度
            //流水号编码
            var maxCodeNumber =
                u8Db
                .Query("VoucherHistory").Where("CardNumber", CardNumber)
                .Select("cNumber")
                .Get<string>().FirstOrDefault();

            //var maxCTVCode =
            //    u8Db.Query("TransVouch").Where("cTVCode", "like", "000%").Max<string>("cTVCode");

            //获取新增后流水号编码
            cNumber = (string.IsNullOrEmpty(maxCodeNumber) ? 1 : long.Parse(maxCodeNumber) + 1).ToString();
            var wCode = (string.IsNullOrEmpty(maxCodeNumber) ? 1 : long.Parse(maxCodeNumber) + 1).ToString().PadLeft(int.Parse(GlideLen), '0');
            //获取单据号前缀规则
            var prefix1Code = "";
            #region  获取前缀1规则生成的编码
            var Prefix1 = codeNumberDic["Prefix1"].ToString();//前缀1
            var Prefix1Rule = codeNumberDic["Prefix1Rule"];//前缀1生成规则
            var Prefix1Len = codeNumberDic["Prefix1Len"].ToString();//前缀1长度
            if (Prefix1Rule == null || string.IsNullOrWhiteSpace(Prefix1Rule.ToString()))
            {
                prefix1Code = prefix1Code.PadLeft(int.Parse(Prefix1Len), '0');
            }
            else
            {
                var dateStr = "";
                if (Prefix1Rule.ToString().Equals("年月"))
                {
                    dateStr = DateTime.Now.ToString("yyyyMM");
                }
                if (Prefix1Rule.ToString().Equals("年月日"))
                {
                    dateStr = DateTime.Now.ToString("yyyyMMdd");
                }
                if (dateStr.Length >= int.Parse(Prefix1Len))
                {
                    var start = dateStr.Length - int.Parse(Prefix1Len);
                    prefix1Code = dateStr.Substring(start, int.Parse(Prefix1Len));
                }
                else
                {
                    var start = int.Parse(Prefix1Len) - dateStr.Length;
                    prefix1Code = dateStr.PadLeft(start, '0');
                }
            }
            #endregion
            //拼接单据编码
            cTVCode = prefix1Code + wCode;
            // 获取两个id
            var p = new DynamicParameters();
            //p.Add("")
            var sql_temp = @"
declare @iFatherId int; 
declare @iChildId int; 
exec sp_getid 
@cacc_id= '{0}', 
@cVouchType='{1}', 
@iAmount={2},  
@iFatherId = @iFatherId out, 
@iChildId=@iChildId out; 
select @iFatherId iFatherId,@iChildId iChildId;";
            var sql = string.Format(sql_temp, ConfigReader.Reader["DbName"].Split('_')[1], cVouchType, childNum);

            var outputList = u8Db.Select<output>(sql);

            //fatherId = (int.Parse(outputList.First().iFatherId) + 1).ToString();
            //childId = (int.Parse(outputList.First().iChildId) + 1).ToString();
            //
            fatherId = (int.Parse(outputList.First().iFatherId)).ToString();
            childId = (int.Parse(outputList.First().iChildId)).ToString();

        }
        public class output
        {
            public string iFatherId { get; set; }
            public string iChildId { get; set; }
        }
        /// <summary>
        /// 获取存货显存量数据
        /// </summary>
        /// <param name="proCode"></param>
        /// <param name="warehouseCode"></param>
        /// <param name="color"></param>
        /// <param name="shangbiao"></param>
        /// <returns></returns>
        public static IEnumerable<Models.DbCurrentStock> getPositionStock(string proCode, string warehouseCode, string color, string shangbiao, string goodsPosition)
        {
            var u8Db = new Katabase().U8Db();
            var possibleCollection = u8Db.Query("InvPositionsum")
                   .Where("cInvCode", "=", proCode)
                   .Where("cWhCode", "=", warehouseCode)
                   .Where("cfree1", "=", color)
                   .Where("cfree3", "=", shangbiao)
                   .Where("cPosCode", "=", goodsPosition)
                   .Get<Models.DbCurrentStock>();
            return possibleCollection;
        }
        /// <summary>
        /// 获取存货现存量数据
        /// </summary>
        /// <param name="proCode"></param>
        /// <param name="warehouseCode"></param>
        /// <param name="color"></param>
        /// <param name="shangbiao"></param>
        /// <returns></returns>
        public static IEnumerable<Models.DbCurrentStock> getCurrentStock(string proCode, string warehouseCode, string color, string shangbiao)
        {
            var u8Db = new Katabase().U8Db();
            var possibleCollection = u8Db.Query("CurrentStock")
                   .Where("cInvCode", "=", proCode)
                   .Where("cWhCode", "=", warehouseCode)
                   .Where("cfree1", "=", color)
                   .Where("cfree3", "=", shangbiao)
                   .Get<Models.DbCurrentStock>();
            return possibleCollection;
        }
        public static List<IEnumerable<string>> getDataValue(List<JObject> jsonList, List<string> headList)
        {
            var temList = new List<IEnumerable<string>>();
            if (jsonList != null && jsonList.Count > 0)
            {
                foreach (var item in jsonList)
                {
                    if (headList != null && headList.Count > 0)
                    {
                        var values = new List<string>();
                        foreach (var key in headList)
                        {
                            var value = "";
                            if (item.Property(key) != null)
                            {
                                value = item[key].ToString();
                            }
                            values.Add(value);
                        }
                        temList.Add(values);
                    }
                }
            }
            return temList;
        }
        /// <summary>
        /// 检测货位现存量
        /// </summary>
        /// <param name="proCode"></param>
        /// <param name="warehouseCode"></param>
        /// <param name="color"></param>
        /// <param name="shangbiao"></param>
        /// <param name="goodsPosition"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        public static bool CheckPositionStock(string proCode, string warehouseCode, string color, string shangbiao, string goodsPosition, string number,ref decimal iquantity)
        {
            // 如果是红单，不用判断
            if (Convert.ToDecimal(number) < 0)
            {
                return true;
            }
            var u8Db = new Katabase().U8Db();
            var possibleCollection = u8Db.Query("InvPositionsum")
            .Where("cInvCode", "=", proCode)
            .Where("cWhCode", "=", warehouseCode)
            .Where("cfree1", "=", color)
            .Where("cfree3", "=", shangbiao)
             .Where("cPosCode", goodsPosition)
            .Get<Models.DbCurrentStock>();

            if (possibleCollection.Count() == 0)
            {
                return false;
            }
            else
            {
                iquantity = possibleCollection.Sum(p => decimal.Parse(p.iQuantity));
                if (decimal.Parse(number) <= iquantity)
                {
                    return true;
                }
            }
            return false;
        }
        public static Tuple<bool, decimal> CheckPositionStock_With_iQuantity(string proCode, string warehouseCode, string color, string shangbiao, string goodsPosition, string number)
        {
            // 如果是红单，不用判断
            if (Convert.ToDecimal(number) < 0)
            {
                return new Tuple<bool, decimal>(true, 0.0m);
            }
            var u8Db = new Katabase().U8Db();
            var possibleCollection = u8Db.Query("InvPositionsum")
            .Where("cInvCode", "=", proCode)
            .Where("cWhCode", "=", warehouseCode)
            .Where("cfree1", "=", color)
            .Where("cfree3", "=", shangbiao)
             .Where("cPosCode", goodsPosition)
            .Get<Models.DbCurrentStock>();

            if (possibleCollection.Count() == 0)
            {
                return new Tuple<bool, decimal>(false, 0.0m);
            }
            else
            {
                var iquantity = possibleCollection.Sum(p => decimal.Parse(p.iQuantity));
                if (decimal.Parse(number) <= iquantity)
                {
                    return new Tuple<bool, decimal>(true, iquantity);
                }
                else
                {
                    return new Tuple<bool, decimal>(false, iquantity);
                }
            }
            //return false;
        }
        public static void Set_TransVouch_MainIndex_SubIndex(string cVouchType, string iChildId_input)
        {
            //var cNumber = long.Parse(cTVCode);

            //var iFatherId = long.Parse(iFahterId_input) - 1000000000;
            var iChildId = long.Parse(iChildId_input) - 1000000000;

            var u8Db = new Katabase().U8Db();

            //u8Db.Query("VoucherHistory").Where("CardNumber", "0304").Update(new { cNumber });
            u8Db.Query("UFSystem.dbo.UA_Identity")
                .Where("cAcc_Id", ConfigReader.Reader["DbName"].Split('_')[1])
                .Where("cVouchType", cVouchType).Update(new { iChildId });
        }
        /// <summary>
        /// 添加流水号记录数据表
        /// </summary>
        /// <param name="CardNumber"></param>
        /// <param name="cNumber"></param>
        /// <param name="sqlList"></param>
        public static void insertcNumber(string CardNumber, string cNumber, ref List<DbTable> sqlList)
        {
            #region 添加流水号记录数据
            var names = new List<string>();
            names.Add("CardNumber");
            names.Add("cNumber");
            names.Add("bEmpty");
            var valueList = new List<string>();
            valueList.Add(CardNumber);
            valueList.Add(cNumber);
            valueList.Add("0");
            var list = new List<IEnumerable<string>>
                {
                    valueList
                };
            var dbTable = new DbTable();
            dbTable.tableName = "VoucherHistory";
            dbTable.tableColumns = names;
            dbTable.insertValues = list;
            dbTable.editType = DbTable.otypes.add;
            sqlList.Add(dbTable);
            #endregion
        }
    }
}